import * as vscode from 'vscode';
import { APIData } from './Service/ApiLocation';

export class ApiCodeLensProvider implements vscode.CodeLensProvider {
    private _onDidChangeCodeLenses = new vscode.EventEmitter<void>();
    public readonly onDidChangeCodeLenses: vscode.Event<void> = this._onDidChangeCodeLenses.event;

    private codeLenses: vscode.CodeLens[] = [];

    constructor() {
        // 监听事件以刷新 CodeLens
        vscode.workspace.onDidChangeTextDocument(() => {
            this.clearCodeLenses();
        });
        vscode.window.onDidChangeActiveTextEditor(() => {
            this.clearCodeLenses();
        });
    }

    public addCodeLens(adapterCode: APIData): void {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('未找到活动编辑器');
            return;
        }
        const line = Number(adapterCode.line)-1; // 行号从 0 开始
        const document = editor.document;
        const range = new vscode.Range(
            new vscode.Position(line, 0),
            new vscode.Position(line, document.lineAt(line).text.length)
        );
        this.codeLenses = []; // 清空之前的 CodeLens
        this.codeLenses.push(
            new vscode.CodeLens(range, {
                title: 'AI修复',
                command: 'HarmonyPilot.fixCode',
                arguments: [adapterCode],
            })
        );

        this._onDidChangeCodeLenses.fire();
    }

    public provideCodeLenses(
        document: vscode.TextDocument,
        _: vscode.CancellationToken
    ): vscode.CodeLens[] {
        return this.codeLenses.filter(codeLens => codeLens.range.start.line < document.lineCount);
    }

    public clearCodeLenses(): void {
        this.codeLenses = [];
        this._onDidChangeCodeLenses.fire();
    }

    public handleFixCode(line: number): void {
        // 清除当前 CodeLens
        this.clearCodeLenses();

        // 添加新的 CodeLens，标题为“AI正在努力思考中......”
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('未找到活动编辑器');
            return;
        }

        const document = editor.document;
        const range = new vscode.Range(
            new vscode.Position(line, 0),
            new vscode.Position(line, document.lineAt(line).text.length)
        );

        this.codeLenses.push(
            new vscode.CodeLens(range, {
                title: 'AI正在努力思考中......',
                command: '', // 暂时不绑定命令
            })
        );

        this._onDidChangeCodeLenses.fire();
    }
}